package com.qf.first.controller;

import com.qf.first.entity.Category;
import com.qf.first.pojo.vo.RespVo;
import com.qf.first.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Api(tags = "商品类目模块")
@RestController
@RequestMapping("/category")
public class CategoryController extends BaseController{
    @Autowired
    private CategoryService categoryService;

    @ApiOperation("根据商铺id获取该商铺的所有分类信息")
    @GetMapping("/getCategoriesByShopId")
    public RespVo getCategoriesByShopId(Category category){
        Long shopId = category.getShopId();
        List<Category> categoryList = categoryService.findCategoriesByShopId(shopId);
        return convertSuccess(categoryList);
    }

    @ApiOperation("根据当前分类id删除该分类")
    @GetMapping("/deleteCategory")
    public RespVo deleteCategory(Category category){
        String msg = categoryService.deleteCategory(category);
        return convertSuccess(msg);
    }

    @ApiOperation("添加类目信息")
    @PostMapping(value = "/addCategory",consumes = "multipart/*",headers = "content-type=multipart/form-data")
    public RespVo addCategory(Category category, MultipartFile file, HttpServletRequest request){
        //获取文件名
        String fileName = file.getOriginalFilename();
        //文件名拼接UUID
        fileName = UUID.randomUUID().toString()+"_"+fileName;

        String path = request.getSession().getServletContext().getRealPath("imgs");
        File readPath = new File(path);
        if (!readPath.exists()){
            readPath.mkdirs();
        }
        try {
            file.transferTo(new File(readPath+"/"+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        category.setCategoryUrl(fileName);
        String msg = categoryService.addCategory(category);
        return convertSuccess(msg);
    }

    @ApiOperation("获取所有分类信息")
    @GetMapping("/getAllCategories")
    public RespVo getAllCategories(){
        List<Category> allCategories = categoryService.findAllCategories();
        return convertSuccess(allCategories);
    }
}
